//https://leetcode.cn/problems/clear-digits/description/?envType=daily-question&envId=2024-09-05


class Solution {
public:
    string clearDigits(string s) {
        string ans = "";
        int n = s.size();
        int i = n - 1, j = n - 1;
        while (i >= 0 && j >= 0) {
            while (i >= 0 && isdigit(s[i])) i--;
            while (j >= 0 && !isdigit(s[j])) j--;
            if (i >= 0 && j >= 0) {
                if (j > i) {
                    i--;
                    j--;
                } else {
                    ans.push_back(s[i]);
                    i--;
                }
            }
        }
        reverse(ans.begin(), ans.end());
        if (i >= 0) ans = s.substr(0, i + 1) + ans;
        return ans;
    }
};